<template>
  <div class="role">
    <pageCard :title-name="'角色列表'" :type="'pageTitle'">
      <div class="topText">角色名称：</div>
      <el-input
        v-model="search.roleName"
        placeholder="请输入"
        class="searchInput"
        @keyup.enter.native="searchClick"
      />
      <el-button type="primary" class="topBtn" icon="el-icon-search" @click="searchClick">搜索</el-button>
      <div class="topBtnDiv">
        <el-button type="primary" plain class="topBtn" @click="alertForm('add')">新增</el-button>
      </div>
      <myTable
        ref="myTable"
        style="height: 100%; margin-top: 10px"
        :row-key="'roleId'"
        :table-label="tableLabel"
        :table-data="tableData"
        :table-total-size="tableTotalSize"
        :search-data="searchData"
        @getTableData="getTableData"
        @handleSelectionChange="handleSelectionChange"
        @rowClickChange="rowClickChange"
      >
        <template #isSystem="slotProps">
          <el-tag :type="slotProps.rowValue.isSystem === 1 ? 'success' : 'warning'">
            {{ slotProps.rowValue.isSystem === 1 ? '是' : '否' }}
          </el-tag>
        </template>
        <template #enable="slotProps">
          <el-tag :type="slotProps.rowValue.enable === 0 ? 'info' : 'primary'">
            {{ slotProps.rowValue.enable === 0 ? '禁用' : '启用' }}
          </el-tag>
        </template>
        <template #operating="slotProps">
          <!-- v-permission="['admin', 'editor']" -->
          <el-link
            v-if="slotProps.rowValue.roleId !== 1000"
            :underline="false"
            type="primary"
            @click="alertForm('edit', slotProps.rowValue)"
          >
            修改
          </el-link>
          <el-divider v-if="slotProps.rowValue.roleId !== 1000" direction="vertical"></el-divider>
          <el-link
            v-if="slotProps.rowValue.roleId !== 1000"
            :underline="false"
            type="primary"
            @click="enableRole(slotProps.rowValue)"
          >
            {{ slotProps.rowValue.enable === 1 ? '禁用' : '启用' }}
          </el-link>
          <el-divider v-if="slotProps.rowValue.roleId !== 1000" direction="vertical"></el-divider>
          <el-link
            v-if="slotProps.rowValue.roleId !== 1000"
            :underline="false"
            type="primary"
            @click="alertForm('purview', slotProps.rowValue)"
          >
            设置功能权限
          </el-link>
          <el-divider v-if="slotProps.rowValue.roleId !== 1000" direction="vertical"></el-divider>
          <el-link :underline="false" type="primary" @click="alertForm('user', slotProps.rowValue)">
            管理用户
          </el-link>
          <el-divider v-if="slotProps.rowValue.isSystem !== 1" direction="vertical"></el-divider>
          <el-link
            v-if="slotProps.rowValue.isSystem !== 1"
            :underline="false"
            type="primary"
            style="padding-left: 10px; color: red"
            @click="deleteClick(slotProps.rowValue)"
          >
            删除
          </el-link>
        </template>
      </myTable>
      <pagination
        class="pagination"
        :table-total-size="tableTotalSize"
        :search-data="searchData"
        @getTableData="$refs.myTable.getTableData()"
      />
    </pageCard>
    <setRole
      v-if="['edit', 'add'].includes(pageType)"
      ref="setRole"
      @closeForm="closeForm"
      @submitForm="submitForm"
    />
    <setPurview v-if="pageType === 'purview'" ref="setPurview" @closeForm="closeForm" @submitForm="submitForm" />
    <setRoleUser v-if="pageType === 'user'" ref="setRoleUser" @closeForm="closeForm" />
  </div>
</template>

<script>
import { getRole, deleteRole, addRole, updateRole, enableRole } from '@/api/system-management'
import setRole from './components/setRole'
import setPurview from './components/setPurview'
import setRoleUser from './components/setRoleUser'
import pageCard from '@/components/page/pageCard'
import myTable from '@/components/Table/index'
import pagination from '@/components/Table/pagination'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
import { resetRouterMenu } from '@/router'
export default {
  name: 'Role',
  components: {
    pageCard,
    myTable,
    pagination,
    setRole,
    setPurview,
    setRoleUser
  },
  data() {
    return {
      pageType: 'index',
      search: {
        roleName: ''
      },
      searchData: {
        pageSize: 10,
        currentPage: 1,
        sort: {},
        params: {}
      },
      // table需要的数据
      tableData: [],
      tableLabel: [
        // {
        //   type: 'selection',
        //   width: '55'
        // },
        {
          prop: 'roleId',
          label: '角色ID',
          width: 100,
          showOverflowTooltip: false
        },
        {
          prop: 'roleName',
          label: '角色名称',
          width: 300,
          showOverflowTooltip: true
        },
        {
          prop: 'roleCode',
          label: '角色编码',
          width: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'remark',
          label: '角色描述',
          // minWidth: 120,
          // maxWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'isSystem',
          label: '系统角色',
          width: 100,
          type: 'scope',
          showOverflowTooltip: false
        },
        {
          prop: 'enable',
          label: '状态',
          width: 100,
          type: 'scope',
          showOverflowTooltip: false
        },
        {
          prop: 'operating',
          label: '操作',
          fixed: 'right',
          type: 'scope',
          width: 350,
          showOverflowTooltip: false
        }
      ],
      tableTotalSize: null,
      multipleSelection: [],
      currentRow: {},
      callbackFun: null,
      getRoleRequestId: generateUUID()
    }
  },
  mounted() {
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.getRoleRequestId) {
        let res = e.data.response
        self.tableData = res.data.data
        self.tableTotalSize = res.data.total_count
        self.callbackFun(res.data.data)
      }
    },
    enableRole(row) {
      let title = row.enable === 1 ? '禁用' : '启用'
      this.$confirm('确认要' + title + row.roleName + '角色?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          enableRole({ roleId: row.roleId, enable: Number(!row.enable) }).then((res) => {
            if (res.success) {
              if (this.$store.state.user.roles.includes(row.roleId)) {
                resetRouterMenu()
              }

              this.$notify({
                message: title + '角色成功',
                type: 'success'
              })
              this.$refs.myTable.getTableData()
            } else {
              this.$notify({
                message: res.message,
                type: 'error'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击删除
    deleteClick(row) {
      this.$confirm('确认要删除' + row.roleName + '角色?此操作会同时删除用户配置的角色并不可恢复!', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRole({ roleId: row.roleId }).then((res) => {
            if (this.$store.state.user.roles.includes(row.roleId)) {
              resetRouterMenu()
            }
            this.$notify({
              title: '成功',
              message: '删除角色成功',
              type: 'success'
            })
            this.$refs.myTable.getTableData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击新增或者编辑
    alertForm(type, row) {
      this.pageType = type
      // 这里$nextTick是为了让这个组件先加载然后再使用refs
      this.$nextTick(() => {
        switch (type) {
          case 'edit':
            this.$refs.setRole.is(this.pageType, row)
            break
          case 'add':
            this.$refs.setRole.is(this.pageType)
            break
          case 'purview':
            this.$refs.setPurview.is(row)
            break
          case 'user':
            this.$refs.setRoleUser.is(row)
            break
          default:
            break
        }
      })
    },
    // 提交角色
    submitForm(type, data, refreshMenu) {
      if (type === 'add') {
        addRole(data).then((res) => {
          if (res.success) {
            this.$notify({
              title: '成功',
              message: '新增角色成功',
              type: 'success'
            })
            this.$refs.setRole.closeDialog()
            this.$refs.myTable.getTableData()
          } else {
            this.$notify({
              title: '失败',
              message: res.message,
              type: 'error'
            })
          }
        })
      }
      if (type === 'edit') {
        updateRole(data).then((res) => {
          if (res.success) {
            if (refreshMenu) {
              resetRouterMenu()
            }
            this.$notify({
              title: '成功',
              message: '修改角色成功',
              type: 'success'
            })
            this.$refs.setRole.closeDialog()
            this.$refs.myTable.getTableData()
          } else {
            this.$notify({
              title: '失败',
              message: res.message,
              type: 'error'
            })
          }
        })
      }
    },
    // 关闭表单
    closeForm() {
      this.pageType = 'index'
    },
    // 获取tableData
    getTableData(cab) {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.callbackFun = cab
        this.getRoleRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/role/loadRolePage',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: this.searchData,
          WebInfo: {
            requestId: this.getRoleRequestId
          }
        }
        postMessage(message)
      } else {
        getRole(this.searchData).then((res) => {
          this.tableData = res.data.data
          this.tableTotalSize = res.data.total_count
          cab(res.data.data)
        })
      }
    },
    // 搜索
    searchClick() {
      this.searchData.currentPage = 1
      this.searchData.params['roleName'] = this.search.roleName
      this.$refs.myTable.getTableData()
    },
    // 复选框回调函数
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击行回调函数
    rowClickChange(val) {
      this.currentRow = val
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/pageTableTop.scss';
.role {
  height: 99%;
}
.pagination /deep/.page {
  margin-bottom: -2px;
}
</style>
